package com.ycq.parser.node.parser;

import com.ycq.parser.ImageInfo;
import com.ycq.parser.QuestionNode;
import com.ycq.parser.node.RadioQuestionNode;
import com.ycq.parser.node.ShareQuestionNode;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 共享题干解析器
 *
 * @author ycq
 * @date 2025/9/24 15:18
 */
public class ShareQuestionParser implements ParserProvider{

    public static final Set<String> INCLUDE_WORD_TEXTS = new HashSet<>();
    static{
        INCLUDE_WORD_TEXTS.add("共用题干");
        INCLUDE_WORD_TEXTS.add("共享题干");
    }

    private static Pattern CODE_PATTERN = Pattern.compile("^((\\d{1,3})(\\.|、)?).+");


    RadioQuestionParser radioQuestionParser = new RadioQuestionParser();

    @Override
    public boolean hasSupport(List<String> questionItemLines) {

        /*
               共享题干格式：
                 - 范围
                 - 问题
                 子题1 （单选题格式）
                 子题2 （单选题格式）
         */
        Iterator<String> iterator = questionItemLines.iterator();

        Pattern rangePattern = Pattern.compile("((\\d{1,3})\\s*(~|～|-|—)\\s*(\\d{1,3})).+");

        String start = null;
        String end = null;

        // 第一行
        if(iterator.hasNext()){
            String next = iterator.next().trim();

            if(!hasIncludeWord(next)){
                return false;
            }

            // 题目格式不符合单选
            Matcher matcher = rangePattern.matcher(next);
            if(matcher.find()){
                start = matcher.group(2);
                end = matcher.group(4);
            }
        }
        // 范围参数不全
        if(start==null || end==null){
            return false;
        }

        List<Integer> seqCodes = IntStream.range(Integer.parseInt(start), Integer.parseInt(end) + 1)
                .boxed().collect(Collectors.toCollection(ArrayList::new));

        while(iterator.hasNext()){
            String next = iterator.next().trim();
            Matcher matcher = CODE_PATTERN.matcher(next);
            if(matcher.find()){
                String code = matcher.group(2);
                int seqIntCode = Integer.parseInt(code);
                if(seqCodes.contains(seqIntCode)){
                    seqCodes.remove((Object)seqIntCode);
                }
            }
        }

        // 范围内的所有子题都被解析到了
        return seqCodes.isEmpty();
    }

    private boolean hasIncludeWord(String text) {
        for (String wordText : INCLUDE_WORD_TEXTS) {
            if(text.contains(wordText)){
                return true;
            }
        }
        return false;
    }

    @Override
    public QuestionNode parse(List<String> questionItemLines, List<ImageInfo> imageInfoNode) {

        ShareQuestionNode shareQuestionNode = new ShareQuestionNode();
        shareQuestionNode.setQuestionRange(questionItemLines.get(0));

        StringBuilder questionBuilder = new StringBuilder();
        int offsetIndex = 1;

        for(int i = offsetIndex;i<questionItemLines.size();i++){
            String line = questionItemLines.get(i).trim();
            questionBuilder.append(line);

            // 判断下一行是否为子题，如果不是子题，则视为问题，拼接到问题
            if(i+1<questionItemLines.size()){
                String nextLine = questionItemLines.get(i+1).trim();
                Matcher matcher = CODE_PATTERN.matcher(nextLine);
                if(!matcher.matches()){
                    questionBuilder.append("\n");
                }else{
                    offsetIndex = i+1;
                    break;
                }
            }
        }
        shareQuestionNode.setQuestion(questionBuilder.toString());

        List<RadioQuestionNode> radioQuestionNodes = new ArrayList<>();

        int startIndex = offsetIndex;
        int endIndex = startIndex;
        while(endIndex<questionItemLines.size()){

            String line = questionItemLines.get(endIndex).trim();
            Matcher matcher = CODE_PATTERN.matcher(line);
            if(!matcher.matches()){
                endIndex++;
                continue;
            }

            if(startIndex<endIndex){
                List<String> subLines = questionItemLines.subList(startIndex, endIndex);
                QuestionNode questionNode = radioQuestionParser.parse(subLines, null);
                if(questionNode == null){
                    throw new IllegalArgumentException("共享题干子题解析失败");
                }
                radioQuestionNodes.add((RadioQuestionNode) questionNode);
                startIndex = endIndex;
            }
            endIndex++;
        }
        if(startIndex<endIndex){
            List<String> subLines = questionItemLines.subList(startIndex, endIndex);
            QuestionNode questionNode = radioQuestionParser.parse(subLines, null);
            if(questionNode == null){
                throw new IllegalArgumentException("共享题干子题解析失败");
            }
            radioQuestionNodes.add((RadioQuestionNode)questionNode);
        }
        shareQuestionNode.setRadioQuestionNodes(radioQuestionNodes);
        shareQuestionNode.setImages(imageInfoNode);
        shareQuestionNode.setRawLines(questionItemLines);
        return shareQuestionNode;
    }
}
